<template>
    <div>
        <el-link :underline="false" @click="goTop()">
            <div class="go-top" v-show="top.falg" >
                <i class="el-icon-caret-top"></i> 
            </div>
        </el-link>
    </div>
</template>

<script>
export default {

    data(){
        return{
            top:{
                scrollTop:0,
                falg:false
            }
        }
    },
    methods:{
        watchScroll(){
           
           var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
           console.log(scrollTop);
           this.scrollTop=scrollTop;
           this.top.falg = scrollTop > 500?true:false;

       },
       goTop(){
        console.log('回到顶部~');
        const that = this
        let timer = setInterval(() => {
            let ispeed = Math.floor(-that.scrollTop / 5)
            document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
            if (that.scrollTop === 0) {
            clearInterval(timer)
            }
        }, 16)

       }

    },
    mounted(){
        window.addEventListener("scroll", this.watchScroll);//创建监听器
        
    },
    beforeDestroy(){
        window.removeEventListener("scroll", this.watchScroll);//移除监听器
    }


}
</script>

<style scoped>
.go-top{
    margin-top: -360px;
    margin-left: 96%;
    position: fixed;
    background-color: #fff;
    border-radius: 40px;
    width: 50px;
    height: 50px;
    font-size: 36px;
    line-height: 50px;
    font-weight: 900px;
    color: #409EFF;
    text-align: center;
}

</style>